<?php

abstract class Association extends AssociationDefinition implements IAssociation, ArrayAccess
{

  /**
   *
   * @var array
   */
  protected $meta;

  /**
   *
   * @var boolean
   */
  protected $saveBefore = false;

  /**
   *
   * @var boolean
   */
  protected $saveAfter = false;

  /**
   *
   * @return boolean
   */
  public function saveBefore()
  {
    return $this->saveBefore;
  }

  /**
   *
   * @return boolean
   */
  public function saveAfter()
  {
    return $this->saveAfter;
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/domain/api/IAssociation#delValue($client)
   */
  public function delValue(IAggregate $client)
  {
    $meta = & $this->data($client);

    if (isset($meta['value'])) {
      unset($meta['value']);
    }
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/domain/api/IAssociation#getDefinition()
   */
  public function getDefinition()
  {
    return $this;//->definition;
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/domain/api/IAssociation#hasValue($client)
   */
  public function hasValue(IAggregate $client)
  {
    $meta = & $this->data($client);
    return isset($meta['value']);
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/domain/api/IAssociation#setValue($client, $value)
   */
  public function setValue(IAggregate $client, $value)
  {
    $meta = & $this->data($client);
    $meta['value'] = $value;
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/domain/api/IAssociation#getValue($client)
   */
  public function getValue(IAggregate $client)
  {
    $meta = & $this->data($client);

    if (! isset($meta['value'])) {
      $this->loadData($client);
    }

    return $meta['value'];
  }

  /**
   *
   * @param IAggregate $client
   * @return void
   */
  protected function loadData(IAggregate $client)
  {
  }

  public function beforeSave($name, &$client)
  {
  }

  public function afterSave($name, &$client)
  {
  }

  /**
   *
   * @param IAggregate $client
   * @return array
   */
  protected function &data(IAggregate $client)
  {
    if (! isset($this->meta[$client->getUid()])) {
      $this->meta[$client->getUid()] = array();
    }

    return $this->meta[$client->getUid()];
  }

  public function offsetSet($offset, $value)
  {
    $meta = & $this->data($client);
    $meta['value'][$offset] = $value;
  }

  public function offsetExists($offset)
  {
    $meta = & $this->data($client);
    return isset($meta['value'][$offset]);
  }

  public function offsetUnset($offset)
  {
    $meta = & $this->data($client);
    unset($meta['value'][$offset]);
  }

  public function offsetGet($offset)
  {
    $meta = & $this->data($client);
    return $meta['value'][$offset];
  }

}

?>